/**
*  
* @Function ES连接客户端
* @ProjectName credit-framework-common
* @PackageName com.py.credit.utils.elasticsearch    
* @FileName RestHighLevelClientFactory.java    
* @Date 2018年11月5日下午4:16:06
* @Author Min DongXv
* @Copyright (c) 2018, 金电联行 All Rights Reserved.   
*   
*/  
package com.py.credit.utils.elasticsearch;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.py.framework.core.log.ExceptionLogger;

/**
 * 
 * @Function ES连接客户端
 * @ClassName RestHighLevelClientFactory
 * @Date 2018年10月29日 下午4:31:15
 * @Author Min DongXv
 * 
 */
@Component
public class RestHighLevelClientFactory implements InitializingBean {

	// 默认端口
	private static final int DEFAULT_PORT = 9200;

	private static RestClientBuilder builder;
	// 连接客户端
	private static RestHighLevelClient client;
	// 连接配置 地址配置(格式严格为 IP:PORT|IP:PORT|~ 例： 10.10.136.57:9300|10.10.136.58:9300)
	private static String esHosts;

	private static String userName;

	private static String password;
	
	private RestHighLevelClientFactory() {
	}

	/**
	 *
	 * @Function 初始化连接客户端
	 * @FileName RestHighLevelClientFactory.java
	 * @MethodName getInstance
	 * @Author Min DongXv
	 *
	 */
	public static synchronized RestHighLevelClient getInstance() {
		if (null != builder) {
			client = new RestHighLevelClient(builder);
		} else {
			client = new RestHighLevelClient(init());
		}
		return client;
	}

	private static RestClientBuilder init() {
		if (StringUtils.isNotBlank(esHosts)) {
			HttpHost[] hosts = initHosts();
			CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
			credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(userName, password));
			builder = RestClient.builder(hosts).setHttpClientConfigCallback(
					httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider));
		}
		return builder;
	}

	/**
	 *
	 * @Function 初始化ES地址
	 * @FileName RestHighLevelClientFactory.java
	 * @MethodName initHosts
	 * @Author Min DongXv
	 *
	 */
	public static HttpHost[] initHosts() {
		if (StringUtils.isNotBlank(esHosts)) {
			String[] hosts = StringUtils.split(esHosts, "|");
			List<HttpHost> hostList = new ArrayList<>(hosts.length);
			for (String s : hosts) {
				String[] ips = StringUtils.split(s, ":");
				if (null != ips && ips.length >= 2 && StringUtils.isNotBlank(ips[1])) {
					int ipPort = Integer.parseInt(ips[1]);
					int port = ipPort > 0 ? ipPort : DEFAULT_PORT;
					HttpHost host = new HttpHost(ips[0], port, HttpHost.DEFAULT_SCHEME_NAME);
					hostList.add(host);
				}
			}
			HttpHost[] httpHosts = new HttpHost[hostList.size()];
			return hostList.toArray(httpHosts);
		}
		return new HttpHost[0];
	}

	/**
	 *
	 * @Function 关闭连接
	 * @FileName RestHighLevelClientFactory.java
	 * @MethodName closeClinet
	 * @Author Min DongXv
	 *
	 */
	public static void closeClinet() {
		if (null != client) {
			try {
				client.close();
			} catch (IOException e) {
				ExceptionLogger.error("RestHighLevelClientFactory#closeClinet", "关闭ES连接客户端异常！ERROR:" + e.getMessage());
			}
		}
	}

	/**
	 * @param hostStr
	 *            the hostStr to set
	 */
	@Value("${esHosts}")
	public void setHostStr(String hosts) {
		esHosts = hosts;
	}

	/**
	 * @param userName
	 *            the userName to set
	 */
	@Value("${esUserName}")
	public void setUserName(String esUserName) {
		userName = esUserName;
	}

	/**
	 * @param password
	 *            the password to set
	 */
	@Value("${esPassword}")
	public void setPassword(String esPassword) {
		password = esPassword;
	}

	@Override
	public void afterPropertiesSet() throws Exception {

	}
}
